package org.baitu.zzim.config;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.baitu.zzim.netty.NettyChannelInitializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * @author zhangkai_a
 * @date 2025/7/2 09:43
 */
@Configuration
public class NettyConfig {

    @Autowired
    private NettyChannelInitializer channelInitializer;

    @Autowired
    private NettyProperties properties;

    @Bean(destroyMethod = "shutdownGracefully")
    public EventLoopGroup bossGroup() {
        return new NioEventLoopGroup(properties.getBossThreads());
    }

    @Bean(destroyMethod = "shutdownGracefully")
    public EventLoopGroup workerGroup() {
        return new NioEventLoopGroup(properties.getWorkerThreads());
    }

    @Bean
    public ServerBootstrap serverBootstrap() {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup(), workerGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(channelInitializer)
                .option(ChannelOption.SO_BACKLOG, properties.getBacklog())
                .childOption(ChannelOption.SO_KEEPALIVE, properties.isKeepAlive());
        return b;
    }

    @Bean
    public ChannelFuture channelFuture() throws Exception {
        return serverBootstrap().bind(properties.getPort()).sync();
    }
}